﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using MovieRental.Entities;
using MovieRental.SqlRepositoryLibrary.Helpers;

namespace MovieRental.SqlRepositoryLibrary.Converters
{
    public class EditionConverter : BaseConverter<EditionInfo, Guid>
    {
        protected override SqlEntityMapping SetUpMapping()
        {
            var mapping = new SqlEntityMapping("Editions", "Id");
            mapping.AddProperty("Id", "Id", SqlDbType.UniqueIdentifier);
            mapping.AddProperty("MovieId", "MovieId", SqlDbType.UniqueIdentifier);
            mapping.AddProperty("MediaTypeId", "MediaTypeId", SqlDbType.UniqueIdentifier);
            mapping.AddProperty("DiscountId", "DiscountId", SqlDbType.UniqueIdentifier);
            mapping.AddProperty("Publisher", "Publisher", SqlDbType.NVarChar);
            mapping.AddProperty("PricePerDay", "PricePerDay", SqlDbType.Float);
            mapping.AddProperty("Quantity", "Quantity", SqlDbType.Int);
            return mapping;
        }

        protected override void SetUpPropertyValues(EditionInfo entity)
        {
            SetProperty("Id", entity.Id);
            SetProperty("MovieId", entity.MovieId);
            SetProperty("MediaTypeId", entity.MediaTypeId);
            SetProperty("DiscountId", (entity.DiscountId == Guid.Empty) ? (object) DBNull.Value : (object)entity.DiscountId);
            SetProperty("Publisher", entity.Publisher);
            SetProperty("PricePerDay", entity.PricePerDay);
            SetProperty("Quantity", entity.Quantity);
        }

        public override EditionInfo ConvertFromDataReader(SqlDataReader reader)
        {
            Guid id = (Guid)GetValueForProperty(reader, "Id");
            EditionInfo edition = new EditionInfo(id);
            edition.MovieId = (Guid)GetValueForProperty(reader, "MovieId");
            edition.MediaTypeId = (Guid)GetValueForProperty(reader, "MediaTypeId");
            var discount = GetValueForProperty(reader, "DiscountId");
            edition.DiscountId = (discount == DBNull.Value) ? Guid.Empty : (Guid)discount; 
            edition.Publisher = (string)GetValueForProperty(reader, "Publisher");
            edition.PricePerDay = (double)GetValueForProperty(reader, "PricePerDay");
            edition.Quantity = (int)GetValueForProperty(reader, "Quantity");
            return edition;
        }
    }
}
